package cn.wizzer.myfiles.pinyin;

import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Files;
import org.nutz.lang.Strings;
import org.nutz.lang.Tasks;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author wizzer.cn
 */
@IocBean
public class MyFilesHandler {
    private final static Log log = Logs.get();
    private String dir = "";
    private String to = "";
    private int skip = 1;
    private int level = 0;
    private static StringBuilder dir_list = new StringBuilder();
    private static StringBuilder file_list = new StringBuilder();
    private int time = 0;

    public void init() {
        dir = System.getenv("DIR");
        to = System.getenv("TO");
        skip = Integer.parseInt(Strings.sBlank(System.getenv("SKIP"), "1"));
        level = Integer.parseInt(Strings.sBlank(System.getenv("LEVEL"), "5"));
        // dir = "/Users/wizzer/temp";
        // to = "/Users/wizzer/temp";
        time = Integer.parseInt(Strings.sNull(System.getenv("TIME"), "3600"));
        if (Strings.isBlank(dir)) {
            log.error("扫描目录未配置");
            return;
        }
        if (Strings.isBlank(to)) {
            log.error("保存路径未设置");
            return;
        }
        // 延迟5秒执行
        Tasks.scheduleAtFixedRate(this::run, 5, time, TimeUnit.SECONDS);
    }

    public void run() {
        String[] dirs = Strings.splitIgnoreBlank(dir, ",");
        for (String d : dirs) {
            long a = System.currentTimeMillis();
            this.initList();
            log.info("扫描 " + d);
            this.listFile(d, 0, 0, -1, "");
            String dirname = d.substring(d.lastIndexOf("/"));
            String saveDirName = to + "/" + dirname + "_dir.txt";
            String saveFileName = to + "/" + dirname + "_file.txt";
            Files.write(saveDirName, dir_list.toString());
            Files.write(saveFileName, file_list.toString());
            this.initList();
            log.infof("扫描 %s 完成,耗时:%dms", d, (System.currentTimeMillis() - a));
        }
    }

    public void listFile(String path, int lv, int index, int pindex, String pfix) {
        if (lv > level) {
            return;
        }
        File[] files = Files.lsAll(path, null);
        if (files != null) {
            List<File> fileList = Arrays.asList(files);
            Collections.sort(fileList, new Comparator<File>() {
                @Override
                public int compare(File o1, File o2) {
                    if (o1.isDirectory() && o2.isFile())
                        return -1;
                    if (o1.isFile() && o2.isDirectory())
                        return 1;
                    return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase());
                }
            });
            String nowfix = "";
            if (pindex == 0) {
                nowfix = pfix + " ";
            } else if (pindex > 0) {
                nowfix = pfix + "| ";
            }
            String line = nowfix + (pindex >= 0 ? "|-" : "");
            int i = fileList.size();
            for (File file : fileList) {
                if (file.exists()) {
                    if (skip == 1 && (file.getName().startsWith("@") || file.getName().startsWith("."))) {
                        i--;
                        continue;
                    }
                    if (file.isDirectory()) {
                        dir_list.append(line + file.getName() + "\r\n");
                        file_list.append(line + file.getName() + "\r\n");
                        this.listFile(file.getAbsolutePath(), lv + 1, i, index, nowfix);
                    }
                    if (file.isFile()) {
                        file_list.append(line + file.getName() + "\r\n");
                    }
                }
                i--;
            }
        }
    }

    public void initList() {
        dir_list.delete(0, dir_list.length());
        file_list.delete(0, file_list.length());
    }

}
